/*
 * Copyright 2004-2006 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package uk.co.foocode.sample.petclinic.web.controller;

import java.util.Collection;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import uk.co.foocode.sample.petclinic.web.form.VisitSearchForm;

/**
 * JavaBean Form controller that is used to search for <code>Owner</code>s by
 * last name.
 * 
 * @author Ken Krebs
 */
public class FindVisitsFormController extends AbstractClinicFormController {
 

    /** Creates a new instance of FindOwnersForm */
    public FindVisitsFormController() {
        setCommandClass(VisitSearchForm.class);
    }
 
    protected Object formBackingObject(HttpServletRequest request)
    		throws Exception {
    	 VisitSearchForm form = new VisitSearchForm();
    	 // default in the start/end dates
    	 form.setStartDate(new Date());
    	 form.setEndDate(DateUtils.addMonths(new Date(), 1));
    	 return form;
    }
    /**
     * Method used to search for owners renders View depending on how many are
     * found
     */
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
            BindException errors) throws Exception {
    	
    	VisitSearchForm form = (VisitSearchForm) command;
        // find owners by last name
        Collection results = getClinic().findVisits(form.getStartDate(), form.getEndDate());
        if (results.size() < 1) {
            // no owners found
            errors.reject("notFound", null, "not found");
            return showForm(request, response, errors);
        }
        Map model = errors.getModel();
        model.put("visits",results);
        
        return new ModelAndView(getSuccessView(),model);
    }
    protected boolean isFormSubmission(HttpServletRequest request) {
    	return super.isFormSubmission(request)|| request.getParameterMap().size()>0;
    }
}
